package com.linmo.personalcenter;

import com.linmo.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DialogueDatabaseManage {

    private static final Logger log = LoggerFactory.getLogger(DialogueDatabaseManage.class);

    // 加载数据库中的对话库
    public List<DialogueDTO> loadDialogueLibrary() {
        List<DialogueDTO> dialogueLibrary = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection()) {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT id, question, answer FROM questions");

            while (rs.next()) {
                int id = rs.getInt("id");
                String question = rs.getString("question");
                String answer = rs.getString("answer");
                dialogueLibrary.add(new DialogueDTO(id, question, answer));
            }

        } catch (SQLException e) {
            log.error("加载问题数据库出错", e);
            throw new RuntimeException(e);
        }
        return dialogueLibrary;
    }

    // 添加问答数据
    public void addDialogue(String question, String answer) {
        String sql = "INSERT INTO questions (question, answer) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, question);
            pstmt.setString(2, answer);
            pstmt.executeUpdate();
            log.info("添加问题数据库成功");
        } catch (SQLException e) {
            log.error("添加问题数据库出错", e);
            throw new RuntimeException(e);
        }
    }

    // 删除问答数据
    public void deleteDialogue(int id) {
        String sql = "DELETE FROM questions WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, id);
            pstmt.executeUpdate();
            log.info("删除问题数据库成功");
        } catch (SQLException e) {
            log.error("删除问题数据库出错", e);
            throw new RuntimeException(e);
        }
    }

    // 更新问答数据
    public void updateDialogue(int id, String question, String answer) {
        log.info("更新问题数据库ing");
        String sql = "UPDATE questions SET question = ?, answer = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, question);
            pstmt.setString(2, answer);
            pstmt.setInt(3, id);
            pstmt.executeUpdate();
            log.info("更新问题数据库成功");
        } catch (SQLException e) {
            log.error("更新问题数据库出错", e);
            throw new RuntimeException(e);
        }
    }
}